package com.qiu.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiu.usercenter.common.ErrorCode;
import com.qiu.usercenter.exception.ExceptionUtils;
import com.qiu.usercenter.manager.ServiceRequests;
import com.qiu.usercenter.mapper.QuestionMapper;
import com.qiu.usercenter.model.domain.AiRequest.ChatMessage;
import com.qiu.usercenter.model.domain.AiRequest.Config;
import com.qiu.usercenter.model.domain.Question;
import com.qiu.usercenter.model.domain.User;
import com.qiu.usercenter.service.QuestionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author QIU
 * @description 针对表【question(题目)】的数据库操作Service实现
 * @createDate 2025-03-06 02:05:50
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question>
        implements QuestionService {

    private final QuestionMapper questionMapper;

    public QuestionServiceImpl(QuestionMapper questionMapper) {
        this.questionMapper = questionMapper;
    }

    /**
     * AI 生成题目
     *
     * @param stage           年级
     * @param count_direction 题目数量
     * @param direction       什么类型的题
     * @return boolean
     */
    @Transactional
    @Override
    public boolean getQuestion(String ChatId, String stage, int count_direction, String direction) {
        if (StringUtils.isAnyBlank(stage, direction)) {
            ExceptionUtils.error(ErrorCode.PARAM_NOT_NULL);
        }

        Config config = new Config(
                "fastgpt-2Hlwk8Eqk41jexjs7SuYRmyaurqym9Qyb8waRmUlcy8p2XaYIduEsEQdn7Z3q1Ph",
                "fastgpt-2Hlwk8Eqk41jexjs7SuYRmyaurqym9Qyb8waRmUlcy8p2XaYIduEsEQdn7Z3q1Ph"
        );

        // 进行AI网络请求
        ServiceRequests serviceRequests = new ServiceRequests(config);
        System.out.println(config.getCharset());

//        String chatId = System.getenv("CHAT_ID");
        String chatId = ChatId;
        String prompt = "学习阶段{" + stage + "}，数量{" + count_direction + "}，学科范围{" + direction + "}";
        List<ChatMessage> msg = Collections.singletonList(new ChatMessage(prompt));
        // 调用 chatCompletions 方法
        Map<String, Object> ret = serviceRequests.chatCompletions(chatId, true, null, msg);

        if (ret == null) {
            ExceptionUtils.error(ErrorCode.Request_ERROR, "AI生成问题失败【可能是上下文到上限了？更换CharId】？【模型正在加载】");
        }
        System.out.println("========================================");
        // 提取 choices 列表
        List<Map<String, Object>> choices = (List<Map<String, Object>>) ret.get("choices");

        if (choices == null) {
            ExceptionUtils.error(ErrorCode.Request_ERROR, "AI生成问题失败【可能是上下文到上限了？更换CharId】？【模型正在加载】");
        }
        // 获取第一个 choice
        Map<String, Object> firstChoice = choices.get(0);

        // 提取 message
        Map<String, Object> message = (Map<String, Object>) firstChoice.get("message");

        // 提取 content
        String content = (String) message.get("content");

        // 输出 content
//        System.out.println(content);
        String[] split = content.split("\n");
        // 使用 forEach 遍历并打印每个分割后的字符串
        // 使用批量插入
        List<Question> questionList = new ArrayList<>();

        Arrays.stream(split).forEach(question_ -> {
            String trim = Optional.ofNullable(question_).map(String::trim).orElse(""); // 使用Optional处理空值
            if (!trim.isEmpty()) { // 检查非空
                Question question = new Question();
                question.setTags("[\\待审核\\]");
                question.setTitle(stage + direction);
                question.setUserid(5);
                question.setContent(trim);
                questionList.add(question); // 添加到批量插入列表
            }
        });
        // 使用事务管理批量插入
        boolean saveResult = this.saveBatch(questionList); // 假设saveBatch是批量插入方法
        if (!saveResult) {
            ExceptionUtils.error(ErrorCode.SQL_ERROR, "[AI生成问题]插入数据失败");
        }
        return true;
    }


    public List<Question> getAllQuestion(int userId) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);

        List<Question> questionList = questionMapper.selectList(queryWrapper);

        if (questionList == null || questionList.isEmpty()) {
            ExceptionUtils.error(ErrorCode.SQL_ERROR, "数据库里没有数据");
        }

        return geySafetyQuestion(questionList);
    }

    public List<Question> geySafetyQuestion(List<Question> questionList) {
        List<Question> safetyQuestionList = new ArrayList<Question>();
        questionList.forEach(question -> {
            Question safetyQuestion = new Question();
            safetyQuestion.setId(question.getId());
            safetyQuestion.setTitle(question.getTitle());
            safetyQuestion.setContent(question.getContent());
            safetyQuestion.setTags(question.getTags());
            safetyQuestion.setUserid(question.getUserid());
            safetyQuestion.setCreatetime(question.getCreatetime());
            safetyQuestionList.add(safetyQuestion);
        });
        return safetyQuestionList;
    }


}




